﻿using System;
using System.Globalization;
using System.Web.Services;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.Constants;
using Monkey.Warrenty.EntityModel;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.InstantTickets
{
    public partial class Edit : System.Web.UI.Page
    {
        #region Properties

        private static InstantTicketBiz _instantTicketBiz;
        private static InstantTicketBiz InstantTicketManager
        {
            get { return _instantTicketBiz ?? (_instantTicketBiz = new InstantTicketBiz()); }
        }

        private static CustomerBiz _customerBiz;
        private static CustomerBiz CustomerManager
        {
            get { return _customerBiz ?? (_customerBiz = new CustomerBiz()); }
        }

        private int _ticketId;
        private int TicketId
        {
            get
            {
                if (_ticketId <= 0)
                    int.TryParse(Request.QueryString["id"], out _ticketId);
                return _ticketId;
            }
        }

        private InstantTicket _instantTicket;
        private InstantTicket CurrentTicket
        {
            get
            {
                if (_instantTicket == null && TicketId > 0)
                {
                    _instantTicket = InstantTicketManager.GetById(TicketId);
                }
                return _instantTicket;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (WarrantyCommon.CurrrentEmployee == null)
            {
                Response.Redirect("~/Logon.aspx");
                return;
            }

            if (!WarrantyCommon.CurrrentEmployee.HasRole(RoleConstant.AdminDichVu))
            {
                Response.Redirect("~/NoPermission.aspx");
            }

            if (!IsPostBack)
            {
                if (CurrentTicket == null)
                {
                    errorMessage.Visible = true;
                    lblErrorMessage.Text = string.Format("{0}: Id={1}", Resources.GlobalStrings.NotExisted, TicketId);
                }
                else
                {
                    // common
                    txtCode.Text = CurrentTicket.Code;
                    txtReceivedDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", CurrentTicket.CreatedDate);
                    txtContent.Text = CurrentTicket.TicketContent;
                    txtDistance.Text = string.Format("{0:0.00}", CurrentTicket.Distance);
                    txtDescription.Text = CurrentTicket.Description;

                    // customer
                    var customer = CustomerManager.GetById(CurrentTicket.CustomerId);
                    if (customer != null)
                    {
                        txtName.Enabled = false; txtEmail.Enabled = false; txtAddress.Enabled = false; txtPhone.Enabled = false;
                        txtName.Text = customer.Name;
                        txtEmail.Text = customer.Email;
                        txtAddress.Text = customer.Address;
                        txtPhone.Text = customer.Phone;
                    }

                    // load employees
                    //var employees = InstantTicketManager.GetEmployees();
                    //ddlEmployees.DataSource = employees;
                    //ddlEmployees.DataValueField = "Id";
                    //ddlEmployees.DataTextField = "Name";
                    //ddlEmployees.DataBind();
                    //ddlEmployees.SelectedValue = CurrentTicket.CreatedEmployeeId.ToString(CultureInfo.InvariantCulture);

                    // load customers groups
                    //var groups = CustomerManager.GetAllCustomerGroups();//_repository.CityRepository.GetAllCustomerGroups();
                    //groups.Insert(0, new CustomerGroup { Id = 0, Name = Resources.GlobalStrings.AllGroups });
                    //ddlCustomerGroups.DataValueField = "Id";
                    //ddlCustomerGroups.DataTextField = "Name";
                    //ddlCustomerGroups.DataSource = groups;
                    //ddlCustomerGroups.DataBind();

                    // load states
                    var states = InstantTicketManager.GetTicketStates();
                    ddlTicketStatus.DataSource = states;
                    ddlTicketStatus.DataValueField = "Id";
                    ddlTicketStatus.DataTextField = "Name";
                    ddlTicketStatus.DataBind();
                    ddlTicketStatus.SelectedValue = CurrentTicket.StatusId.ToString(CultureInfo.InvariantCulture);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            errorMessage.Visible = false;
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var code = txtCode.Text.Trim();
            if (code.Length == 0)
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.CodeIsRequired;
                return;
            }
            DateTime createdDate;
            if (!DateTime.TryParseExact(txtReceivedDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDate))
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }
            //var createdDate = new DateTime(tmpCreatedDate.Year, tmpCreatedDate.Month, tmpCreatedDate.Day, tmpCreatedDate.Hour, tmpCreatedDate.Minute, 0); // workaround for SQL 2005

            //if (ddlEmployees.SelectedIndex < 0)
            //{
            //    errorMessage.Visible = true;
            //    lblErrorMessage.Text = Resources.GlobalStrings.ReceivedEmployeeRequired;
            //    return;
            //}
            var ticketContent = txtContent.Text.Trim();
            if (ticketContent.Length == 0)
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.TicketContentRequired;
                return;
            }

            double distance;
            double.TryParse(txtDistance.Text.Trim(), out distance);

            //CurrentTicket.Code = code;
            CurrentTicket.CreatedDate = createdDate;
            //CurrentTicket.CreatedEmployeeId = int.Parse(ddlEmployees.SelectedValue);
            CurrentTicket.TicketContent = ticketContent;
            CurrentTicket.Distance = distance;
            CurrentTicket.StatusId = int.Parse(ddlTicketStatus.SelectedValue);
            CurrentTicket.Description = txtDescription.Text;

            // call biz save ticket
            InstantTicketManager.UpdateTicket(CurrentTicket);

            errorMessage.Visible = true;
            lblErrorMessage.Text = Resources.GlobalStrings.UpdateSuccess;
        }

        protected void btnCopyToWarranty_Click(object sender, EventArgs e)
        {
            var copiedWarrantyId = InstantTicketManager.CopyToWarranty(CurrentTicket.Id);
            Response.Redirect(string.Format("~/WarrantyTickets/Edit.aspx?id={0}", copiedWarrantyId));
        }

        #endregion

        #region WS methods

        [WebMethod(EnableSession = true)]
        public static object TicketProductList(long ticketId)
        {
            var ticketProducts = InstantTicketManager.GetTicketProducts(ticketId);
            return new { Result = "OK", Records = ticketProducts };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketDeleteProduct(int Id)
        {
            InstantTicketManager.DeleteTicketProduct(Id);
            return new { Result = "OK" };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketServiceList(long ticketId)
        {
            var ticketServices = InstantTicketManager.GetTicketServices(ticketId);
            return new { Result = "OK", Records = ticketServices };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketDeleteService(int Id)
        {
            InstantTicketManager.DeleteTicketService(Id);
            return new { Result = "OK" };
        }

        #endregion

        #region Employee Methods

        [WebMethod(EnableSession = true)]
        public static object TicketEmployeeList(long ticketId)
        {
            var ticketEmployees = InstantTicketManager.GetTicketEmployees(ticketId);
            return new { Result = "OK", Records = ticketEmployees };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketDeleteEmployee(int Id)
        {
            InstantTicketManager.DeleteTicketEmployee(Id);
            return new { Result = "OK" };
        }

        #endregion
    }
}